const { exec } = require('../db/index')
const { getPassword } = require('../utils/crypto')
const { SuccessModel, FailModel } = require('../utils/resModel')

class UserService {
  async login(ctx) {
    // 获取 账号 密码 匹配数据库
    const { username, password } = ctx.request.body;
    // 如果是字符串 ，一定要加引号
    let data = await exec(`select * from users where username='${username}' and password='${getPassword(password)}'`)
    if (data.length) {
      return { ...SuccessModel, data };
    } else {
      return { ...FailModel, tip: '请注册' };
    }
  }

  async register(ctx) {
    // 获取参数
    const { username, password, nickname } = ctx.request.body;
    let data = await exec(`select * from users where username='${username}' and password='${getPassword(password)}'`)
    if (data.length) {
      return { ...FailModel, tip: '用户名已经存在' }
    } else {
      let insertData = await exec(`insert into users (username, password, nickname) values ('${username}','${getPassword(password)}', '${nickname}')`)
      // 返回增加的数据id
      return { ...SuccessModel, insertId: insertData.insertId }
    }
  }

  async findAll(ctx) {
    console.log(ctx.request.header.token, 'header')
    let data = await exec(`select title, content,createtime from blogs`)
    // 返回查到的所有数据
    return { ...SuccessModel, data }
  }

  async add(ctx) {
    const { title, content, author, userid } = ctx.request.body;
    let data = await exec(`insert into blogs (title, content, author, userid) values ('${title}','${content}','${author}', ${userid})`)
    // 返回增加的数据id
    return { ...SuccessModel, id: data.insertId }
  }

  async update(ctx) {
    const { title, content, author, userid, id } = ctx.request.body;
    let data = await exec(`update blogs set title='${title}', content='${content}',author='${author}',userid=${userid} where id=${id}`)
    return { ...SuccessModel, affectedRows: data.affectedRows };
  }

  async delete(ctx) {
    const { id } = ctx.request.body;
    let data = await exec(`delete from blogs where id=${id}`)
    return { ...SuccessModel, affectedRows: data.affectedRows }
  }
}


module.exports = new UserService